<template>
  <div>

    <!-- 1.定义面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>账号管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2.定义卡片视图 -->
    <el-card class="box-card">

      <!-- 3.定义栅格的一行 :gutter="20"定义行间距   :span="9" 占位符  -->
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 3.定义搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getRoleList">
            <el-button slot="append" icon="el-icon-search" @click="getRoleList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 定义添加按钮-->
          <el-button type="primary" @click="dialogVisible = true">添加管理员</el-button>
        </el-col>
      </el-row>

      <!-- 用户数据表格展现  border 边框线属性
            :data="userList"  动态获取userList集合,用于表格数据展现
            label=显示的字段的名称
            prop="动态获取属性的值"
            status属性的只 不是字符串 是boolean类型 所以不能直接展现.

            知识点:
              作用域插槽: 一般在表格数据展现时,可以动态获取当前行对象.
              用法:
                1.template
                2.slot-scope属性="变量"
        -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="账号"></el-table-column>
        <el-table-column prop="roleNickname" label="名称"></el-table-column>
        <el-table-column prop="sortNum" label="权限等级"></el-table-column>
        <el-table-column prop="roleDuty" label="权限范围"></el-table-column>
        <el-table-column prop="roleStatus" label="状态">
          <!-- <template slot-scope="scope">
                  {{scope.row.status}}
              </template> -->

          <template slot-scope="scope">
            <el-switch v-model="scope.row.roleStatus" @change="updateStatus(scope.row)" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="updateRoleBtn(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRole(scope.row)"></el-button>
          </template>

        </el-table-column>
      </el-table>

      <!-- 定义分页组件 关于分页插件的属性说明
            1.@size-change 如果分页中每页实现的条数发生变化 则会触发这个该事件
            2.@current-change 当页数发生改变时,触发该函数
            3.current-page 当前选中的页
            4.page-sizes   页面数据展现的选项
            5.page-size    默认选中的页数
            6.layout    分页中展现的数据种类
            7.total     记录总数
       -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 20, 40]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 编辑用户新增对话框 visible.sync 控制对话框的显示-->
    <el-dialog title="添加管理员" :visible.sync="dialogVisible" width="50%" @close="closeDialog">

      <!-- 定义用户提交表单数据-->
      <el-form :model="addRoleModel" :rules="rules" ref="addUserRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="账号" prop="roleName">
          <el-input v-model="addRoleModel.roleName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="rolePassword">
          <el-input v-model="addRoleModel.rolePassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="rolePassword2">
          <el-input v-model="addRoleModel.rolePassword2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="roleNickname">
          <el-input v-model="addRoleModel.roleNickname" ></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="sortNum">
          <el-select v-model="addRoleModel.sortNum" placeholder="请选择权限">
            <el-option label="1" value="1">1</el-option>
            <el-option label="2" value="2">2</el-option>
            <el-option label="3" value="3">3</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限范围" prop="roleDuty">
          <el-input v-model="addRoleModel.roleDuty" placeholder="请输入权限范围"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 定义修改页面 当对话框关闭时,将表格数据重置-->
    <el-dialog title="修改管理员" :visible.sync="updateDialogVisible" width="50%" @close="closeUpdateDialog">
      <!-- 定义用户提交表单数据-->
      <el-form :model="updateRoleModel" :rules="rules" ref="updateRoleRef" label-width="100px">
        <el-form-item label="账号" prop="roleName">
          <el-input v-model="updateRoleModel.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="roleNickname">
          <el-input v-model="updateRoleModel.roleNickname"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="sortNum">
          <el-select v-model="updateRoleModel.sortNum" placeholder="请选择权限">
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
            <el-option label="3" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      //校验邮箱规则 rule校验规则   value校验的数据   callback回调函数
      // const checkEmail = (rule, value, callback) => {
      //   //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
      //   const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
      //   //正则表达式语法校验  test(xx) 校验成功 返回true  校验失败返回false
      //   if (emailRege.test(value)) {
      //     //表示邮箱合法 正确返回
      //     return callback()
      //   }
      //   callback(new Error('请填写正确的邮箱地址'))
      // }

      // //校验手机号的邮箱规则
      // const checkPhone = (rule, value, callback) => {

      //   //定义校验手机号的正则语法
      //   const phoneRege = /^1[3-9][0-9]{9}$/
      //   if (phoneRege.test(value)) {

      //     return callback()
      //   }
      //   callback(new Error('请填写正确的手机号'))

      // }

      const checkPassword = (rule, value, callback) => {
        if (this.addRoleModel.rolePassword !== value) return callback(new Error('2次密码输入不一致'))
        //否则校验成功
        callback()
      }

      return {
        queryInfo: {
          query: '',
          pageNum: 1,
          pageSize: 5
        },
        roleList: [],
        //记录总数是数值类型
        total: 0,
        dialogVisible: false,
        addRoleModel: {
          roleName: '',
          rolePassword: '',
          rolePassword2: '',
          roleNickname: '',
          sortNum: '',
          roleDuty: ''
        },
        // dynamicTags: [],
        // inputVisible: false,
        // inputValue: '',
        //数据校验规则
        rules: {
          roleName: [{
              required: true,
              message: '请输入账号',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            }
          ],
          roleNickname: [{
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            }
          ],
          rolePassword: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            }
          ],
          rolePassword2: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPassword,
              trigger: 'blur'
            }
          ],
          sortNum: [{
            required: true,
            message: '请选择权限',
            trigger: 'change'
          }],
          // email: [
          //         { required: true, message: '请输入邮箱', trigger: 'blur' },
          //         { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
          //         { validator: checkEmail , trigger: 'blur' }
          //       ]
        },
        updateDialogVisible: false,
        //定义修改用户数据封装
        updateRoleModel: {}
      }
    },
    methods: {
      async getRoleList() {
        const {
          data: result
        } = await this.$http.get('/role/list', {
          params: this.queryInfo
        })
        if (result.status !== 200) return this.$message.error("管理员列表查询失败")
        this.roleList = result.data.rows
        this.total = result.data.total
        console.log("总记录数:" + this.total)
      },
      async updateStatus(role) {
        //实现用户状态修改  注意使用模版字符串  ES6中提出的新用法 ${key}
        //const {data: result} = await this.$http.put('/user/status/'+user.id+'/'+user.status)
        const {
          data: result
        } = await this.$http.put(`/role/updateRoleStatus/`, role)
        if (result.status !== 200) return this.$message.error("管理员状态修改失败!")
        this.$message.success("管理员状态修改成功!")
      },
      handleSizeChange(pageSize) {
        //console.log("每页展现的条数"+pageSize)
        this.queryInfo.pageSize = pageSize
        this.getRoleList()
      },
      handleCurrentChange(pageNum) {
        //console.log("页数:"+pageNum)
        this.queryInfo.pageNum = pageNum
        this.getRoleList()
      },
      closeDialog() {
        //重置表格数据
        this.$refs.addUserRef.resetFields()
      },
      //校验用户数据
      addRoleBtn() {
        this.$refs.addUserRef.validate(async valid => {
          /* 如果校验不通过, 则返回false  如果校验通过 返回true */
          //console.log(valid)
          //如果校验失败 则停止数据
          if (!valid) return
          //console.log(this.addUserModel)
          const {
            data: result
          } = await this.$http.post('/role/saveRole', this.addRoleModel)
          if (result.status !== 200) return this.$message.error("管理员新增失败")
          this.$message.success("管理员新增成功")
          //关闭对话框
          this.dialogVisible = false
          //重新获取用户列表
          this.getRoleList()
        })
      },
      async updateRoleBtn(role) {
        this.updateDialogVisible = true
        const {
          data: result
        } = await this.$http.get("/role/" + role.roleId)
        if (result.status !== 200) return this.$message.error("管理员查询失败")
        this.updateRoleModel = result.data
      },
      closeUpdateDialog() {
        //重置表格数据
        this.$refs.updateRoleRef.resetFields()
      },
      updateRole() {
        //1.预校验数据
        this.$refs.updateRoleRef.validate(async valid => {
          if (!valid) return this.$message.error("表单验证没有通过")
          //根据接口文档要求封装数据
          let role = {}
          role.roleId = this.updateRoleModel.roleId
          role.roleName = this.updateRoleModel.roleName
          role.roleNickname = this.updateRoleModel.roleNickname
          role.sortNum = this.updateRoleModel.sortNum
          const {
            data: result
          } = await this.$http.put(`/role/updateRole`, role)
          if (result.status !== 200) return this.$message.error("管理员修改失败")
          this.$message.success("管理员修改成功")
          this.updateDialogVisible = false
          this.getRoleList()
        })
      },
      async deleteRole(role) {
        //1.消息确认框
        const result = await this.$confirm('此操作将永久删除 ' + role.roleName + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)

        //如果确认  confirm  如果取消 cancel
        if (result !== 'confirm') {
          return this.$message.info("删除取消")
        }
        const {
          data: result2
        } = await this.$http.delete(`/role/deleteRoleById`, {
          params: {
            id: role.roleId
          }
        })
        if (result2.status !== 200) return this.$message.error("删除失败")
        this.$message.success("删除成功")
        //重新加载 数据
        this.getRoleList()
      },
      //elments-tags
      //   handleClose(tag) {
      //   	this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      //   },

      //   showInput() {
      //   	this.inputVisible = true;
      //   	this.$nextTick(_ => {
      //   		this.$refs.saveTagInput.$refs.input.focus();
      //   	});
      //   },

      //   handleInputConfirm() {
      //   	let inputValue = this.inputValue;
      //   	if (inputValue) {
      //   		this.dynamicTags.push(inputValue);
      //   	}
      //   	this.inputVisible = false;
      //   	this.inputValue = '';
      //   },
    },
    //利用钩子函数实现数据查询
    created() {
      this.getRoleList()
    }
  }
</script>


<style lang="less" scoped>

</style>
